package com.example.materialcostsystembackend.service.impl;

import com.example.materialcostsystembackend.dto.OrderRequest;
import com.example.materialcostsystembackend.dto.OrderItemRequest;
import com.example.materialcostsystembackend.model.OrderItemDetail;
import com.example.materialcostsystembackend.model.OrderSummary;
import com.example.materialcostsystembackend.repository.OrderItemDetailRepository;
import com.example.materialcostsystembackend.repository.OrderRepository;
import com.example.materialcostsystembackend.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.ZoneId;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderItemDetailRepository orderItemDetailRepository;

    public boolean existsByOrderNumber(String orderNumber) {
        return orderItemDetailRepository.existsByOrderNumber(orderNumber);
    }
    private final OrderRepository orderRepository;

    public OrderServiceImpl(OrderRepository orderRepository) {
        this.orderRepository = orderRepository;
    }

    @Override
    public void saveOrder(OrderRequest request) {
        OrderSummary summary = new OrderSummary();
        summary.setOrderNumber(request.getOrderNumber());
        summary.setExportTime(request.getExportTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
        summary.setTotalQuantity(request.getTotalQuantity());
        summary.setTotalCost(request.getTotalCost());

        List<OrderItemDetail> itemDetails = request.getItems().stream().map(itemReq -> {
            OrderItemDetail item = new OrderItemDetail();
            item.setMaterialId(itemReq.getMaterialId());
            item.setMaterialName(itemReq.getMaterialName());
            item.setSpecification(itemReq.getSpecification());
            item.setQuantity(itemReq.getQuantity());
            item.setUnitPrice(itemReq.getUnitPrice());
            item.setTotalPrice(itemReq.getTotalPrice());
            item.setOrderSummary(summary);
            return item;
        }).collect(Collectors.toList());

        summary.setItems(itemDetails);
        orderRepository.save(summary);
    }

    @Override
    public List<OrderSummary> getAllOrders() {
        return orderRepository.findAll();
    }

    @Override
    public void deleteOrder(String orderNumber) {
        orderRepository.deleteById(orderNumber);
    }

    @Override
    public List<OrderItemDetail> getOrderItems(String orderNumber) {
        return orderRepository.findById(orderNumber).map(OrderSummary::getItems).orElse(new ArrayList<>());
    }
}